﻿///**********************************
/// Codeplex: http://jsprototype.codeplex.com/
/// Allrights reserved to Rynn Wang (rynn.wang@live.com)
///**********************************

Array.prototype.remove = function (item) {
    var index = this.indexOf(item);
    if (index >= 0) {
        this.splice(index, 1);
        return true;
    }
    return false;
};
Array.prototype.removeAt = function (index) {
    if (index != undefined && index >= 0) {
        this.splice(index, 1);
        return true;
    }
    return false;
};
Array.prototype.clone = function () {
    return this.concat();
};
Array.prototype.find = function (criteriaObject, onlyFirst) {
    var array = new Array();
    if (criteriaObject && typeof criteriaObject != 'undefined') {
        for (var i = 0; i < this.length; i++) {
            var currentObj = this[i];


            if (typeof criteriaObject == 'object') {
                var failed = false;
                for (var key in criteriaObject) {
                    if (currentObj[key] == undefined || currentObj[key] != criteriaObject[key]) {
                        failed = true;
                        break;
                    }
                }

                if (!failed) {
                    if (onlyFirst) {
                        return currentObj.clone();
                    } else {
                        array.push(currentObj.clone());
                    }
                }
            } else {
                if (currentObj == criteriaObject) {
                    if (onlyFirst) {
                        return currentObj;
                    } else {
                        array.push(currentObj);
                    }
                }
            }
        }
    }

    return onlyFirst ? undefined : array;
};
Array.prototype.containsByKey = function (key, value) {
    if (key && typeof key == 'string' && (value || value == 0)) {
        for (var i = 0; i < this.length; i++) {
            var currentObj = this[i];
            if (currentObj[key] == value) {
                return true;
            }
        }
    }
    return false;
};
Array.prototype.contains = function (criteriaObject) {
    if (typeof criteriaObject != 'undefined') {
        return this.find(criteriaObject, true) != undefined;
    }
    return false;
};
Array.prototype.distinct = function () {
    var thisArray = this;
    var uniqueNewArray = [];
    for (var i = 0; i < thisArray.length; i++) {
        var item = thisArray[i];
        if (!uniqueNewArray.contains(item)) {
            uniqueNewArray.push(item);
        }
    }
    return uniqueNewArray;
};